/* Copyright 2008 Bas van den Berg
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "Equipment.h"

#include "myassert.h"
#include "MudWearable.h"
#include "StringBuilder.h"

using namespace Chronos;
using namespace std;

#define FOREACH_SLOT for (SlotsConstIter iter = slots.begin(); iter != slots.end(); ++iter)

Equipment::~Equipment() {
    FOREACH_SLOT {
        delete iter->second;
    }
}


MudWearable* Equipment::findItem(const string& name) const {
    FOREACH_SLOT {
        MudWearable* item = iter->second;
        if (item->matchesName(name)) return item;
    }
    return 0;
}


MudWearable* Equipment::operator[] (Slot slot) const {
    SlotsConstIter iter = slots.find(slot);
    if (iter == slots.end()) return 0;
    return iter->second;
}


unsigned int Equipment::getWeight() const {
    int weight = 0;
    FOREACH_SLOT {
        weight += iter->second->getWeight();
    }
    return weight;
}


void Equipment::wear(MudWearable* equip) {
    Slot slot = equip->getSlot();
    SlotsConstIter iter = slots.find(slot);
    ASSERT_TRUE(iter == slots.end());
    slots[slot] = equip;
}


void Equipment::remove(MudWearable* equip) {
    SlotsIter iter = slots.find(equip->getSlot());
    ASSERT_FALSE(iter == slots.end());
    slots.erase(iter);
}

static const char ITEMLIST_DELIMITER = ';';

void Equipment::serialize(StringBuilder& buffer) const {
    for (SlotsConstIter iter = slots.begin(); iter != slots.end(); ++iter) {
        iter->second->serialize(buffer);
        buffer << ITEMLIST_DELIMITER;
    }
}


const char* const Equipment::toStr[] = { "head", "neck", "finger", "arm", "leg", "chest" };

